<template>
  <div>
    <BasicTable @register="registerTable" @resize-column="handleResizeColumn">
      <template #toolbar> </template>
      <template #action="{ record }">
        <TableAction
          :actions="[
            {
              icon: 'ant-design:undo-outlined',
              tooltip: '强制回撤',
              onClick: handleRecall.bind(null, record),
              ifShow: () => record.isRecallBtnShow,
            },
            {
              icon: 'ant-design:delete-outlined',
              tooltip: '删除',
              onClick: handleDelete.bind(null, record),
            },
            {
              icon: 'ant-design:retweet-outlined',
              tooltip: '流转',
              onClick: handleWanderAbout.bind(null, record),
            },
            {
              icon: 'ant-design:rotate-right-outlined',
              tooltip: '转交',
              onClick: handleTransmit.bind(null, record),
            },
            {
              icon: 'ant-design:file-exclamation-filled',
              tooltip: '状态',
              onClick: handleStatus.bind(null, record),
            },
          ]"
        />
      </template>
    </BasicTable>
    <TransmitModal @register="registerTransmitModal" @success="handleSuccessTransmitModal" />
    <StatusModal @register="registerStatusModal" @success="handleSuccessStatusModal" />
  </div>
</template>
<script lang="ts">
  import { defineComponent, onMounted, ref, h, watchEffect, nextTick, watch } from 'vue';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useModal } from '/@/components/Modal';
  import { useI18n } from '/@/hooks/web/useI18n';
  const { t } = useI18n();
  import { columns, searchFormSchema } from './ProcessingProcessTable.data';
  import TransmitModal from './transmitModal/TransmitModal.vue';
  import StatusModal from './statusModal/StatusModal.vue';
  import {
    getFlowRunDeliverScript,
    getFlowDelMyAction,
    getFlowRecall,
  } from '/@/api/flowManage/flowManage';

  export default defineComponent({
    components: { BasicTable, TableAction, TransmitModal, StatusModal },
    props: {
      typeCode: {
        type: String,
        default: '',
      },
      curFlowId: {
        type: [String, Number],
        default: '',
      },
      aryMyAction: {
        type: Array,
        default: () => [],
      },
    },
    emits: ['reload-success'],
    setup(props, { emit }) {
      const { createMessage, createConfirm } = useMessage();

      console.log('columns', columns);

      // watchEffect(async () => {
      //   console.log('props.aryMyAction', props.aryMyAction);
      //   await nextTick();
      //   if (props.aryMyAction && props.aryMyAction.length > 0) {
      //     setTableData(props.aryMyAction);
      //   } else {
      //     setTableData([]);
      //   }
      // });

      watch(
        () => props.aryMyAction,
        async () => {
          await nextTick();
          if (props.aryMyAction && props.aryMyAction.length > 0) {
            setTableData(props.aryMyAction);
          } else {
            setTableData([]);
          }
        },
        {
          immediate: true,
        },
      );
      // onMounted(async () => {
      // });
      const currentRecord = ref<Recordable>({});
      const [
        registerTable,
        { reload, setProps, setTableData, updateTableDataRecord, deleteTableDataRecord },
      ] = useTable({
        title: '处理过程',
        columns,
        formConfig: {
          labelWidth: 120,
          schemas: searchFormSchema,
        },
        searchInfo: {
          op: 'search',
        }, //额外的参数
        useSearchForm: false,
        showTableSetting: false,
        bordered: false,
        indexColumnProps: { width: 50 },
        showIndexColumn: true,
        beforeFetch: (info) => {
          let newInfo = info;
          if (newInfo.dates && newInfo.dates.length > 0) {
            newInfo.fromDate = newInfo.dates[0];
            newInfo.toDate = newInfo.dates[1];
            delete newInfo.dates;
          }
          return newInfo;
        },
        immediate: false,
        pagination: false,
        canResize: false,
        actionColumn: {
          width: 160,
          title: '操作',
          dataIndex: 'action',
          slots: { customRender: 'action' },
          fixed: 'right',
        },
        rowKey: 'id',
      });
      //转交
      const [registerTransmitModal, { openModal: openModalTransmit }] = useModal();
      function handleTransmit(record: Recordable) {
        currentRecord.value = record;
        openModalTransmit(true, {
          record,
          typeCode: props.typeCode,
          flowId: props.curFlowId,
          isUpdate: true,
        });
      }
      //转交回调
      const handleSuccessTransmitModal = (obj) => {
        const { userRealNames } = obj;
        currentRecord.value.privRealName = userRealNames;
        updateTableDataRecord(currentRecord.value.id, currentRecord.value);
        emit('reload-success');
      };

      //状态
      const [registerStatusModal, { openModal: openModalStatusModal, setModalProps }] = useModal();
      async function handleStatus(record: Recordable) {
        currentRecord.value = record;
        openModalStatusModal(true, {
          record,
          isUpdate: true,
        });
        setModalProps({ confirmLoading: false, bodyStyle: { height: '100px' } });
      }

      //状态回调
      const handleSuccessStatusModal = (obj) => {
        const { label, value } = obj;
        currentRecord.value.checkStatus = value;
        currentRecord.value.checkStatusName = label;
        updateTableDataRecord(currentRecord.value.id, currentRecord.value);
        // emit('reload-success');
      };

      //流转
      function handleWanderAbout(record) {
        createConfirm({
          iconType: 'warning',
          title: () => h('span', t('common.prompt')),
          content: () => h('span', '您确定要在节点上调用流转事件么'),
          onOk: async () => {
            try {
              const params = {
                myActionId: record.id,
                flowId: props.curFlowId,
              };
              await getFlowRunDeliverScript(params);
              createMessage.success('操作成功');
              // emit('reload-success');
            } catch (err) {
              console.error(err);
            } finally {
            }
          },
        });
      }

      //删除
      const handleDelete = async (record) => {
        createConfirm({
          iconType: 'warning',
          title: () => h('span', t('common.prompt')),
          content: () => h('span', '您确定要删除么'),
          onOk: async () => {
            try {
              const params = {
                delMyActionId: record.id,
              };
              await getFlowDelMyAction(params);
              createMessage.success('操作成功');
              deleteTableDataRecord(record.id);
              // emit('reload-success');
            } catch (err) {
              console.error(err);
            } finally {
            }
          },
        });
      };

      //回撤
      const handleRecall = (record) => {
        createConfirm({
          iconType: 'warning',
          title: () => h('span', t('common.prompt')),
          content: () => h('span', '您确定要强制回撤么'),
          onOk: async () => {
            try {
              const params = {
                myActionId: record.id,
              };
              await getFlowRecall(params);
              createMessage.success('操作成功');
              emit('reload-success');
            } catch (err) {
              console.error(err);
            } finally {
            }
          },
        });
      };

      function handleSuccess() {
        reload();
      }
      onMounted(() => {});
      return {
        registerTable,
        handleTransmit,
        handleStatus,
        handleSuccess,
        handleWanderAbout,
        handleResizeColumn: (w, col) => {
          col.width = w;
        },
        registerTransmitModal,
        handleSuccessTransmitModal,
        registerStatusModal,
        handleSuccessStatusModal,
        handleDelete,
        handleRecall,
      };
    },
  });
</script>
